package com.icesoft.core.web.suppose.safehttp.filter;

import com.icesoft.core.common.exception.CheckNoLogException;
import com.icesoft.core.web.excption.RequestException;
import com.icesoft.core.web.suppose.safehttp.service.CryptoKeyPairService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@AllArgsConstructor
@Slf4j
@Component
public class SafeRequestCryptoService {
    private static final ThreadLocal<String> signThreadLocal = new ThreadLocal<>();

    private final CryptoKeyPairService cryptoKeyPairService;

    public String getSign() {
        String sign = signThreadLocal.get();
        assert sign != null;
        return sign;
    }

    public void decryptSign(String keyId, String sign) {
        sign = cryptoKeyPairService.privateDecrypt(keyId, sign);
        signThreadLocal.set(sign);
    }

    public String decryptReqBody(String body) throws CheckNoLogException {
        String key = getSign();
        log.trace("key={}", key);
        if (key.length() != 16 && key.length() != 32) {
            log.info("密钥长度错误:{}", key);
            throw new RequestException("密钥长度错误");
        }
        String params;
        try {
            params = cryptoKeyPairService.getCryptoService().symmetricDecrypt(key, body);
        } catch (IllegalArgumentException e) {
            log.info("解析出错，密文：{}", body);
            throw new RequestException("数据解密出错，请检查加密数据是否正确");
        }
        return params;
    }

    public String encryptRespData(String data) {
        String sign = getSign();
        return cryptoKeyPairService.getCryptoService().symmetricEncrypt(sign, data);
    }

    public void clearSign() {
        signThreadLocal.remove();
    }
}
